package service

import (
	"bbs-web/internal/domain"
	"bbs-web/internal/repository/dao"
	"bbs-web/internal/repository/user"
	"context"
	"errors"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"math/rand"
	"regexp"
	"time"
)

type IuserService interface {
	SignUp(ctx context.Context, user domain.UserInfo) error
	Login(ctx context.Context, user domain.UserInfo) (*dao.UserMode, error)
	CreateUser(ctx context.Context, user domain.UserInfo) (*dao.UserMode, error)
	//SearchUserList(ctx context.Context, search vo.UserSearchReq) (*dao.UserMode, error)
}

type userService struct {
	repo user.IuserRepo
}

func NewUserService(repo user.IuserRepo) IuserService {
	return &userService{repo: repo}
}

func (u *userService) SignUp(ctx context.Context, user domain.UserInfo) error {
	timestamps := time.Now().Unix()
	randomNum := 1000 + rand.Intn(9000)
	nickname := fmt.Sprintf("用户%d%d", timestamps, randomNum)

	encodedPwd, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
	if err != nil {
		return errors.New("密码加密失败")
	}

	user.NickName = nickname
	user.Password = string(encodedPwd)
	err = u.repo.RegUser(ctx, user)
	if err != nil {
		return err
	}
	return nil
}

func (u *userService) Login(ctx context.Context, user domain.UserInfo) (*dao.UserMode, error) {
	data, err := u.repo.LoginCheck(ctx, user)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func (u *userService) CreateUser(ctx context.Context, user domain.UserInfo) (*dao.UserMode, error) {
	// 需要判断电话合不合法
	check := regexp.MustCompile(`^1[3456789]\d{9}$`).MatchString(user.Phone)
	if !check {
		return nil, errors.New("电话号码格式不合法")
	}
	timestamps := time.Now().Unix()
	randomNum := 1000 + rand.Intn(9000)
	nickname := fmt.Sprintf("用户%d%d", timestamps, randomNum)
	user.NickName = nickname
	data, err := u.repo.CreateUser(ctx, user)
	if err != nil {
		return nil, err
	}
	return data, nil
}

//func (u *userService) SearchUserList(ctx context.Context, search vo.UserSearchReq) (*dao.UserMode, error) {
//
//}
